package service

import (
	"fmt"
	"pmservice/db"
	"pmservice/dbfactory"
	"time"

	"pmservice/graph/model"

	gonanoid "github.com/matoous/go-nanoid/v2"
)

// TokenService --
type TokenService struct {
	Orm *dbfactory.ORM
}

// CreateTokenService --
func CreateTokenService(orm *dbfactory.ORM) *TokenService {
	return &TokenService{
		Orm: orm,
	}
}

func (s *TokenService) GenerateToken(uid, username, password, usertype string) *model.Token {
	now := time.Now().Local()
	t := db.Token{
		UserUID:  uid,
		Token:    gonanoid.Must(),
		CreateAt: now,
		ExpireAt: now.Add(time.Duration(time.Hour * 300)),
		UserName: username,
		UserType: usertype,
	}
	result := s.Orm.DB.Create(&t)
	if result.Error != nil {
		fmt.Println("err:", "创建token失败")
		return nil
	}
	return t.ToGQL()
}

func (s *TokenService) ClearToken(token string) {
	s.Orm.DB.Where("token=?", token).Delete(&db.Token{})
}

func (s *TokenService) GetToken(token string) (*db.Token, error) {
	t := db.Token{}
	result := s.Orm.DB.Where("token=?", token).Take(&t)
	if result.Error != nil {
		return nil, result.Error
	}
	return &t, nil
}
